package grammar;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;

/**
 * @author lizen
 */
public class FunctionalSample {
    public static void test() {
        Consumer<String> saySomething = (x) -> System.out.println("Hello, " + x);
        saySomething.accept("World!");

        Supplier<String> getGreeting = () -> "Hello, world!";
        System.out.println(getGreeting.get());

        Function<Integer, String> converter = (number) -> "Number: " + number;
        System.out.println(converter.apply(42));

        Predicate<Integer> greaterThan5 = (x) -> x > 5;
        System.out.println(greaterThan5.test(5));

        // customer
        Function<Integer, Integer> multiplyBy2 = x -> x * 2;
        Function<Integer, Integer> add3 = x -> x +3;

        Function<Integer, Integer> composed = multiplyBy2.andThen(add3);
        System.out.println(composed.apply(2));


        testCustom();

    }

    public static void testCustom() {
        StringProcessor toUpper = String::toUpperCase;
        StringProcessor addPrefix = s -> "PRE_" + s;

        toUpper.showInfo();
        System.out.println(toUpper.process("hello"));  // 输出: HELLO
        System.out.println(addPrefix.process("world")); // 输出: PRE_world
    }

    @FunctionalInterface
    interface StringProcessor {
        String process(String input);

        default void showInfo() {
            System.out.println("This is a text processor");
        }
    }
}
